#include "statistics.hxx"

#include "utility.hxx"
#include "mymutex.hxx"
#include "task.hxx"

#include <sstream>

Statistics* Statistics::instance = 0;

Statistics* Statistics::GetInstance(void)
{
	static Mutex mutex;

	if (instance == 0)
	{
		Utility::Lock lock(&mutex);
		if (instance == 0)
		{
			instance = new Statistics();
		}
	}

	return instance;
}

void Statistics::StaIt(const Task* task)
{
	StaUnit* staUnit = NULL;
	std::map<string, StaUnit*>::iterator iter = staMap.find(task->Signature());
	if (iter == staMap.end())
	{
		staUnit = new StaUnit();
		staUnit->start = time(0);
		staMap[task->Signature()] = staUnit;
	}
	else
		staUnit = iter->second;

	switch (task->CurAction)
	{
	case Task::QUERY:
		{
			++(staUnit->queryNum);
			if (task->ActionRes == Task::ACTION_RESULT_CAPTCHA_WRONG)
				++(staUnit->wrongCaptchaNum);
			else if (task->ActionRes != Task::ACTION_RESULT_NO_FOUND)
				++(staUnit->errorNum);
		}
		break;
	case Task::REFRESH:
		++(staUnit->sustainedNum);
		break;
	default:
		// no statistics for other action.
		break;
	}
}
std::string Statistics::GetStatictics(const Task* task)
{
	StaUnit* staUnit = NULL;
	stringstream ss;

	std::map<string, StaUnit*>::iterator iter = staMap.find(task->Signature());
	if (iter == staMap.end())
	{
		ss<<task->Signature()<<" no statistics.";
		return ss.str();
	}

	staUnit = iter->second;
	ss<<task->Signature()<<" "<<time(0)-staUnit->start<<"s,"
	  <<"query:"<<staUnit->queryNum<<",wrongCap:"<<staUnit->wrongCaptchaNum<<",err:"<<staUnit->errorNum<<",refresh:"<<staUnit->sustainedNum;

	return ss.str();
}